// index.ts
// 获取应用实例
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
import { setUserInfo,getUserInfo } from "../../api/user"
import { upLoadImage } from '../../hooks/upLoadFile'
Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    showLoading:true
  },
  async onChooseAvatar(e: any): Promise<void> {
    const { avatarUrl } = e.detail
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
    })
    const result: string | null = await upLoadImage(avatarUrl);
    if (result?.length) {
      const param: userInfo = {
        name: this.data.userInfo.nickName,
        avatarUrl: result
      }
      // 更新用户信息
      const res = await setUserInfo(param)
      if (res.code) {
        wx.showToast({
          title: "用户信息更新失败",
          icon: "error",
          duration: 1500, // 提示持续的时间，单位毫秒，默认1500
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "success",
          duration: 1500, // 提示持续的时间，单位毫秒，默认1500
        })
      }
    }
  },
  async onInputChange(e: any): Promise<void> {
    const nickName = e.detail.value
    if(nickName === this.data.userInfo.nickName) {
      return      
    }
    this.setData({
      "userInfo.nickName": nickName,
    })
    // 掉接口更新name信息
    if (this.data.userInfo.nickName.length) {
      const param: userInfo = {
        name: this.data.userInfo.nickName,
        avatarUrl: this.data.userInfo.avatarUrl
      }
      const res = await setUserInfo(param);
      if (res.code) {
        wx.showToast({
          title: "用户信息更新失败",
          icon: "error",
          duration: 1500, // 提示持续的时间，单位毫秒，默认1500
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "success",
          duration: 1500, // 提示持续的时间，单位毫秒，默认1500
        })
      }
    }
  },
  getUserProfile(): void {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  toAbout(): void {
    wx.navigateTo({
      url: "/pages/about/about"
    })
  },
  toSuggest(): void {
    wx.navigateTo({
      url: "/pages/suggest/suggest"
    })
  },
  async onLoad(): Promise<void> {
    // 获取用户头像和姓名信息展示
    const result = await getUserInfo() 
    this.setData({
      'userInfo.avatarUrl':result.data?.avatarUrl?result.data?.avatarUrl:defaultAvatarUrl,
      "userInfo.nickName": result.data?.name,
      showLoading: false
    })
  }
})
